import express, { Request, Response } from 'express';
import { SensorHourlyData } from '../entity/SensorHourlyData';
import { AppDataSource } from '../config/database';
import { authenticateJWT } from '../middleware/authMiddleware';
import { Between } from 'typeorm';
import { Device } from '../entity/Device';

const sensorRouter = express.Router();
// sensorRouter.use(express.json());

/**
 * 查询设备最近24小时某指标的传感器记录
 */
sensorRouter.get('/sensor-data/last24h', authenticateJWT, async (req: Request, res: Response) => {
    const userId = (req as any).user.userId;
    const deviceId = req.query.device_id as string;
    const metricType = req.query.metric_type as string;

    if (!deviceId || !metricType) {
        res.status(400).json({message: '缺少参数 device_id 或 metric_type'});
        return;
    }

    // 参数请求验证
    const deviceRepo = AppDataSource.getRepository(Device);
    const device = await deviceRepo.findOne({where: {did: deviceId, userId}});

    if (!device) {
        res.status(404).json({message: '查询设备不存在'});
        return;
    }
    const SENSOR_TYPES = ['mi_temp_hum_sensor', 'mi_air_sensor'];
    const SENSOR_FIELDS: Record<string, string[]> = {
        mi_temp_hum_sensor: ['temperature', 'humidity'],
        mi_air_sensor: ['temperature', 'humidity', 'pm25']
    };

    if (!SENSOR_TYPES.includes(device.type)) {
        res.status(400).json({message: '设备不支持传感器数据查询'});
        return;
    }

    const allowedMetrics = SENSOR_FIELDS[device.type];
    if (!allowedMetrics?.includes(metricType)) {
        res.status(404).json({message: '查询属性不存在'});
        return;
    }


    try {
        const now = new Date();
        const start = new Date(now);
        start.setHours(start.getHours() - 24);
        start.setMinutes(0, 0, 0);

        const repo = AppDataSource.getRepository(SensorHourlyData);

        const records = await repo.find({
            where: {
                deviceId,
                metricType,
                hourStart: Between(start, now)
            },
            order: {
                hourStart: 'ASC'
            }
        });

        res.json({
            device_id: deviceId,
            metric_type: metricType,
            data: records.map(r => ({
                hour: r.hourStart.toISOString(),
                value: r.metricValue
            }))
        });
        return;
    } catch (err: any) {
        res.status(500).json({message: '查询失败', error: err.message});
        return;
    }
});

export default sensorRouter;
